package com.blb.dao.user.impl;

import com.blb.dao.user.DeliverAddressDao;
import com.blb.pojo.UserAddress;
import com.blb.utils.JDBCUtils;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

@Repository
public class DeliverAddressDaoImpl implements DeliverAddressDao {

    @Override
    public List<UserAddress> selectUserAddress() throws Exception {
        Connection connection = JDBCUtils.getConnection();
        String sql = "select * from t_user_address";
        List<UserAddress> list = JDBCUtils.getList(connection, UserAddress.class, sql);
        connection.close();
        return list;
    }

    @Override
    public void updateDefault(int id) throws SQLException, ClassNotFoundException {
        Connection connection = JDBCUtils.getConnection();
        JDBCUtils.prepareStatement(connection,"update t_user_address set is_default = 0").executeUpdate();
        String sql = "update t_user_address set is_default = 1 where id = ? ";
        JDBCUtils.prepareStatement(connection, sql, id).executeUpdate();
        connection.close();
    }

    @Override
    public void insertAddress(UserAddress a) throws SQLException, ClassNotFoundException {
        Connection connection = JDBCUtils.getConnection();
        String sql = "insert into t_user_address (" +
                "user_id,name,tel,province,city,area,detailed_address,is_default) values (?,?,?,?,?,?,?,?) ";

        if (a.getIsDefault() == null){
            a.setIsDefault("0");
        }else {
            JDBCUtils.prepareStatement(connection,"update t_user_address set is_default = 0").executeUpdate();
            a.setIsDefault("1");
        }
        JDBCUtils.prepareStatement(connection,sql,a.getUserId(),a.getName(),a.getTel(),a.getProvince(),a.getCity(),a.getArea(),a.getDetailedAddress(),a.getIsDefault()).executeUpdate();
        connection.close();
    }

    @Override
    public List<UserAddress> updateAddressById(String id) throws Exception {
        Connection connection = JDBCUtils.getConnection();
        List<UserAddress> list = JDBCUtils.getList(connection, UserAddress.class, "select * from t_user_address where id = ?", id);
        connection.close();
        return list;
    }
}
